import type { CompanyInfoDto, PeriodInfoDto } from '@/api/company/types'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { AnyObject } from '@/types'
import { Component, Prop } from 'vue-facing-decorator'
import type { VxeColumnSlotTypes, VxeGridPropTypes, VxeTableDataRow } from 'vxe-table'
import toNative from '@/utils/toNative'
import type { FilterDto } from '@/render/FilterRender'
import {
    getKeyToEnum,
    LevelCnEnum,
    MonthModeCnEnum,
    PolicyStatusCnEnum
} from '@/const/enum'
import {
    exporProved,
    exporProvedPdf,
    exporStaff,
    exportStaffRecord,
    getInsuranceStaffList
} from '@/api/insurance/period'
import type {
    InsuraceStaffDto,
    InsuraceStaffReqDto,
} from '@/api/insurance/period/types'
import { getPeriodCompanySolutionList } from '@/api/insurance/company'
import { downloadFile } from '@/utils/util'
import type { TagType } from '@/api/types'
import { Button, message, Popover, Tag } from 'ant-design-vue'

@Component
export class InsurancePeople extends TableRender {
    @Prop() basicData!: PeriodInfoDto
    @Prop() companyBasicInfo!: CompanyInfoDto

    noTablePadding = true
    noFilterPadding = true
    filterTheme = 'light'

    showVideoDialog = false
    curItem = {}
    videoList = [] as string[]

    filterConfig() {
        return {
            serveCompanyName: {
                name: '派遣单位',
                element: 'input',
                span: 24
            },
            insurCompany: {
                name: '保司名称',
                element: 'select',
                span: 24,
                optionsType: 'insurCompany',
                callback: {
                    change: async (ev: string) => {
                        this.filters.companyPlanName.value = ''
                        this.filters.companyPlanName.options = []
                        if (!ev) return
                        const res = await getPeriodCompanySolutionList({
                            insureCompany: ev
                        })
                        this.filters.companyPlanName.options = res.map((i) => {
                            return {
                                label: i.dictLabel,
                                value: i.dictValue
                            }
                        })
                    }
                }
            },
            companyPlanName: {
                name: '保司方案',
                element: 'select',
                span: 24,
                options: []
            },
            occupationLevel: {
                name: '客户风险等级',
                element: 'radioGroup',
                span: 24,
                options: getKeyToEnum(LevelCnEnum, true)
            },
            occupationOriginLevel: {
                name: '保司风险等级',
                element: 'radioGroup',
                span: 24,
                options: getKeyToEnum(LevelCnEnum, true)
            },
            isMonthMode: {
                name: '月单模式',
                element: 'radioGroup',
                span: 24,
                options: getKeyToEnum(MonthModeCnEnum, true)
            },
            policyStatus: {
                name: '保险状态',
                element: 'radioGroup',
                span: 24,
                options: getKeyToEnum(PolicyStatusCnEnum, true)
            },
            userName: {
                name: '投保人姓名',
                element: 'input',
                span: 12
            },
            idCardNo: {
                name: '身份证号',
                element: 'input',
                span: 12
            },
            insurStartTime: {
                name: '开始时间',
                element: 'datetime',
                span: 12,
                params: {
                    type: 'date',
                    valueFormat: 'YYYY-MM-DD'
                }
            },
            insurEndTime: {
                name: '结束时间',
                element: 'datetime',
                span: 12,
                params: {
                    type: 'date',
                    valueFormat: 'YYYY-MM-DD'
                }
            },
            exportTime: {
                name: '导出时间',
                element: 'datetime',
                type: 'daterange',
                span: 12,
                params: {
                    type: 'date',
                    valueFormat: 'YYYY-MM-DD'
                }
            }
        } as FilterDto
    }

    tableConfig() {
        const config = super.tableConfig()
        config.height = '400px'
        return config
    }

    tableColumnConfigOld = () => [
        {
            field: 'userName',
            title: '投保人',
            width: 160,
            fixed: 'left',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    const typeMap = {
                        0: 'success',
                        1: 'primary',
                        2: 'danger'
                    }
                    return (
                        <div>
                            <div class="flex items-center">
                                <Tag
                                    color={
                                        typeMap[row.policyStatus as keyof typeof typeMap] as TagType
                                    }
                                >
                                    {PolicyStatusCnEnum[row.policyStatus]}
                                </Tag>
                                <div class="ml-10px">{row.userName}</div>
                            </div>
                            <div class="mt-10px">{row.idCardNo}</div>
                        </div>
                    )
                }
            }
        },
        {
            field: 'serveCompanyName',
            title: '派遣单位'
        },
        {
            field: 'companyPlanName',
            title: '方案名称'
        },
        {
            field: 'occupationName',
            title: '工种'
        },
        {
            field: 'price',
            title: '单价'
        },
        {
            field: 'isMonthMode',
            title: '模式',
            formatter: ({ row }) => {
                return MonthModeCnEnum[row.isMonthMode]
            },
        },
        {
            field: 'occupationLevel',
            title: '工种等级'
        },
        {
            field: 'occupationOriginName',
            title: '实际工种名称',
            width: 120
        },
        {
            field: 'occupationOriginLevel',
            title: '实际工种等级',
            width: 120
        },
        {
            field: 'code',
            title: '工种编码'
        },
        {
            field: 'createTime',
            title: '创建时间',
            width: 160
        },
        {
            field: 'insurStartTime',
            title: '生效时间',
            width: 160
        },
        {
            field: 'insurEndTime',
            title: '结束时间',
            width: 160
        }
    ] as TableRenderColumnTypes<InsuraceStaffDto>

    onShowVideo(list: string[]) {
        this.videoList = list
        this.showVideoDialog = true
    }

    getData() {
        this.onPage({
            type: 'current',
            currentPage: 1
        })
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        if (!this.basicData?.companyId) return []
        return getInsuranceStaffList({
            companyId: this.basicData.companyId,
            pageNum: page,
            pageSize: size,
            isDelete: 0,
            ...filters
        })
    }
    async onExportStaff() {
        const res = await exportStaffRecord({
            companyId: this.basicData.companyId,
            isDelete: 0,
            ...this.getFilters()
        })
        downloadFile(res)
    }

    createFilters() {
        return new Promise((resolve, reject) => {
            const data = this.getFilters()
            if (!data.insurCompany || !data.exportTime?.length) {
                message.warning('保险名称与导出时间不能为空')
                reject(false)
            } else {
                data.companyId = this.basicData.companyId
                data.isDelete = 0
                data.queryStartDate = data.exportTime[0]
                data.queryEndDate = data.exportTime[1]
                delete data.exportTime
                delete data.pageNum
                delete data.pageSize
                resolve(data)
            }
            reject(data)
        })
    }

    async onExportProved(type: string) {
        const filters = (await this.createFilters()) as InsuraceStaffReqDto
        const map = {
            pdf: exporProvedPdf,
            ex: exporProved,
            staff: exporStaff
        }
        const res = await map[type as keyof typeof map]({
            ...filters
        })
        downloadFile(res, type === 'pdf')
    }

    renderRightBtns() {
        return (
            <div class="flex flex-wrap gap-10px -mr-20px">
                <div>
                    <Button type="primary" onClick={this.onExportStaff}>
                    导出列表
                    </Button>
                </div>

                <Popover
                    trigger="click"
                    v-slots={{
                        reference: () => {
                            return <Button ghost>导出在保证明</Button>
                        },
                        default: () => {
                            return (
                                <div>
                                    <div
                                        class="text-center cursor-pointer hover:text-blue-default mb-12px"
                                        onClick={() => this.onExportProved('pdf')}
                                    >
                                        PDF
                                    </div>
                                    <div
                                        class="text-center cursor-pointer hover:text-blue-default"
                                        onClick={() => this.onExportProved('ex')}
                                    >
                                        EX
                                    </div>
                                </div>
                            )
                        }
                    }}
                ></Popover>
                <div>
                    <Button ghost onClick={() => this.onExportProved('staff')}>
                    导出在保证明人员
                    </Button>
                </div>
            </div>
        )
    }

    render() {
        return (
            <>
                <div class="bg-white-dark-100 text-base px-12px py-8px mb-12px">投保人员</div>
                <div>{super.render()}</div>
            </>
        )
    }
}

export default toNative<
    { basicData: PeriodInfoDto; companyBasicInfo: CompanyInfoDto },
    { refresh: () => void }
        >(InsurancePeople)
